#---
# Parts (login/logout) excerpted from "Agile Web Development with Rails, 2nd Ed.",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material, 
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose. 
# Visit http://www.pragmaticprogrammer.com/titles/rails2 for more book information.
#---
#
require "digest/sha1"

class Submitter < ActiveRecord::Base
	has_many					      :events_submitters,	:dependent => :destroy
	has_many					      :events,			      :through => :events_submitters

  attr_accessible           :name, :password, :description, :is_administrator
  validates_uniqueness_of   :name
  validates_presence_of     :name, :password

  before_destroy :dont_destroy

  # Return the User with the given name and plain-text password
  def self.login(name, password)
    find(:first, :conditions => { :name => name, :password => hash_password(password || "") } )
  end

  # Log in if the name and password (after hashing) match the database, or
  # if the name matches an entry in the database with no password
  def try_to_login
    Submitter.login(self.name, self.password)
  end

  # When a new User is created, it initially has a plain-text password.
  # We convert this to an SHA1 hash before saving the user in the database.
  def before_create
    self.password = Submitter.hash_password(self.password)
  end

  # Don't delete a certain set of names from the database
  def dont_destroy
    raise "Can't destroy Hurt Reynolds" if self.name =~ /hurt reynolds/i
    raise "Can't destroy Mister Piston" if self.name =~ /mister piston/i
  end

  # Clear out the plain-text password once we've saved this row.
  # This stops it being made available in the session
  def after_create
    @password = nil
  end

  def is_admin?
    return is_administrator
  end

private

  def self.hash_password(password)
    Digest::SHA1.hexdigest(password)
  end

end

# vi:ts=2:et:sw=2:
